package com.party.admin.web.controller.charge;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.charge.PackagePrivilege;
import com.party.core.model.charge.ProductPackage;
import com.party.core.model.charge.ProductPrivilege;
import com.party.core.service.charge.IPackagePrivilegeService;
import com.party.core.service.charge.IPackageService;
import com.party.core.service.charge.IPrivilegeService;
import com.party.core.utils.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 套餐权限
 */
@Controller()
@RequestMapping("charge/packagePrivilege")
public class PackagePrivilegeController {
    @Autowired
    private IPackagePrivilegeService packagePrivilegeService;
    @Autowired
    private IPackageService packageService;
    @Autowired
    private IPrivilegeService privilegeService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 套餐权限列表
     *
     * @param p1
     * @param p2
     * @param commonInput
     * @param page
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(ProductPrivilege p1, PackagePrivilege p2, CommonInput commonInput, Page page) {
        // 套餐
        page.setLimit(20);
        ProductPackage productPackage = packageService.get(p2.getPackageId());
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        params.put("packageId", p2.getPackageId());
        params.put("name", p1.getName());
        params.put("code", p1.getCode());
        List<Map<String, Object>> listMaps = packagePrivilegeService.webListPage(params, page);
        List<Map<String, Object>> newListMaps = Lists.newArrayList();
        for (Map<String, Object> map : listMaps) {
            String parentId = map.get("parentId") != null ? map.get("parentId").toString() : "";
            if (StringUtils.isNotEmpty(parentId) && parentId.equals("0")) {
                newListMaps.add(map);
            }
        }

        for (Map<String, Object> pp : newListMaps) {
            List<Map<String, Object>> childrens = Lists.newArrayList();
            for (Map<String, Object> cc : listMaps) {
                if (pp.get("id") != null && cc.get("parentId") != null && cc.get("parentId").equals(pp.get("id"))) {
                    childrens.add(cc);
                }
            }
            pp.put("childrens", childrens);
        }

        ModelAndView mv = new ModelAndView("charge/packagePrivilege/pprivilegeList");
        mv.addObject("dbPackage", productPackage);
        mv.addObject("privileges", newListMaps);
        mv.addObject("page", page);
        mv.addObject("input", commonInput);
        return mv;
    }

    /**
     * 套餐权限增加
     *
     * @param packageId    套餐id
     * @param pprivilegeId 产品权限id
     * @return
     */
    @RequestMapping("toForm")
    public ModelAndView toForm(String packageId, String pprivilegeId) {
        ModelAndView mv = new ModelAndView("charge/packagePrivilege/pprivilegeForm");
        if (StringUtils.isNotEmpty(pprivilegeId)) {
            PackagePrivilege packagePrivilege = packagePrivilegeService.get(pprivilegeId);
            mv.addObject("packagePrivilege", packagePrivilege);
            packageId = packagePrivilege.getPackageId();

            ProductPrivilege productPrivilege = privilegeService.get(packagePrivilege.getPrivilegeId());
            mv.addObject("productPrivilege", productPrivilege);
        }

        ProductPackage productPackage = packageService.get(packageId);
        mv.addObject("dbPackage", productPackage);

        List<ProductPrivilege> productPrivileges = privilegeService.list(new ProductPrivilege("0"));
        mv.addObject("privileges", productPrivileges);
        return mv;
    }

    /**
     * 套餐权限保存
     *
     * @param packagePrivilege
     * @param privilegeParentId 父级权限
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("save")
    public AjaxResult save(PackagePrivilege packagePrivilege, String privilegeParentId) {
        try {
            String parentId = "";
            // 保存父级
            Map<String, Object> params = Maps.newHashMap();
            params.put("privilegeId", privilegeParentId);
            params.put("packageId", packagePrivilege.getPackageId());
            PackagePrivilege privilegeParent = packagePrivilegeService.findByPackage(params);
            if (privilegeParent == null) {
                PackagePrivilege pp = new PackagePrivilege(packagePrivilege.getPackageId(), privilegeParentId);
                pp.setParentId("0");
                parentId = packagePrivilegeService.insert(pp);
            } else {
                parentId = privilegeParent.getId();
            }

            if (StringUtils.isEmpty(packagePrivilege.getId())) {
                packagePrivilege.setParentId(parentId);
                packagePrivilegeService.insert(packagePrivilege);
            } else {
                PackagePrivilege dbPrivilege = packagePrivilegeService.get(packagePrivilege.getId());
                MyBeanUtils.copyBeanNotNull2Bean(packagePrivilege, dbPrivilege);
                packagePrivilegeService.update(dbPrivilege);
            }
            return AjaxResult.success((Object) packagePrivilege.getPackageId());
        } catch (Exception e) {
            logger.error("套餐权限保存异常：{}", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult delete(String id, String parentId) {
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(parentId)) {
            return AjaxResult.error("ID不能为空");
        }
        try {
            packagePrivilegeService.delete(id);
            List<PackagePrivilege> packagePrivileges = packagePrivilegeService.list(new PackagePrivilege(parentId));
            if (packagePrivileges.size() == 0) {
                packagePrivilegeService.delete(parentId);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除套餐权限异常：{}", e);
            return AjaxResult.error(e.getMessage());
        }
    }
}
